
$(document).ready(function() {
	var init=false;        //设置是否初次加载，若初次加载，则按资源树按用户自动展开
	var globalResId;       //用来记录非异步展开的组织ID，防止加载慢的时候，点击面包屑上别的组织，加载慢的组织形成的树会覆盖已有的组织树
	var needExpandOrgIds=userOrgPath.split(',');    //主要用于在面包屑级别为0的情况展开组织到用户所在组织
    var tempFoc = true;//控制选中之后不显示下拉筛选列表。
    var selectedView = -1;
	var realId = 0;
	var bigLevel = level;
	var onlineMap = {};
	var onlineReady = false;
	var orgArrayLevel = [];
    function toggleViews(view, id) {
        var text = $('[data-view-id="' + id + '"]').text();
        $('[data-trigger="folder.view"]').each(function(idx, item) {
            $('#monResource').removeClass($(item).attr('data-view')).find('.ico').remove();
        });
        $('#monResource').addClass(view);
        $('[data-view-id="' + id + '"]').prepend('<span class="ico i-checked"></span>').parents('.btn-group').find('.buttonS')
                .text(text).append('<span class="caret"></span>');
    }

    /**
     * 将数组src中的值copy到dest数组中
     * src: 原数组
     * dest：目标数组
     */
    function pushAll(src, dest) {
        if (src && src.length) {
            for (i = 0; i < src.length; i++) {
                dest.push(src[i]);
            }
        }
    }
    
    /**
     * 重新加载树
     * id: 组织导航上显示的最后一个组织id,资源树加载该组织下的资源
     * level:组织导航上显示的最后一个组织在完整资源树上的层级 
     * maxLevel:组织导航能够显示的最大的层级
     */
    function reLoadTree(id, level, maxLevel) {   	
        var treea = $("#zTreea").tree();
        if (treea)
            treea.destroy();

        $("#zTreea").show();
        $("#zTreea").parent().find('.msg-tips.nodata').remove();
        $("#zTreea").html("<div class=\"grid4\" style=\"padding-top:50px;\"><div class=\"loading\"><i></i><span>"+language['vms.preview.preview.js.loading']+"</span></div></div>");
        if (!settingRes) {
            settingRes = getSettingRes();
        }
        globalResId=id;
        
        if(level==1&&maxLevel==0){
        	$.fn.zTree.init($("#zTreea"), settingRes, resourceGroup);
        	var updateNode={};
        	getUpdateInitNode(resourceGroup,updateNode);
        	updateOnlineInfoLabel(onlineMap,updateNode);   	
        }else {
        	(function (){          //该段匿名方法用于防止某组织加载速度慢导致用户重点另一个组织，而加载慢的组织在加载完之后覆盖已有的组织树
        		var orgId=id;
        		var curLevel=level;
        		var OrgTreeResult = {
        		        "id": "20",
        		        "label": "陵水县",
        		        "isParent": true,
        		        "cls": "town",
        		        "parentId": "1",
        		        "children": null,
        		        "extra": {
        		            "auth": 2,
        		            "orgCode": "46902800",
        		            "type": "org"
        		        },
        		        "checked": false,
        		        "chkDisabled": false,
        		        "isHidden": false,
        		        "open": false
        		    };
        		var OrgTreeData = [{"id":"camera-44","label":"塔吊","isParent":false,"cls":"ico m-ball","parentId":"107","children":null,"extra":{"channelNo":1,"indexCode":"001130","ezvizCameraCode":null,"fav":0,"realId":"44","type":"res","orgId":107,"installWay":null},"checked":false,"chkDisabled":false,"isHidden":false,"open":false,"relationName":null},{"id":"camera-43","label":"加工厂","isParent":false,"cls":"ico m-ball","parentId":"107","children":null,"extra":{"channelNo":1,"indexCode":"001129","ezvizCameraCode":null,"fav":0,"realId":"43","type":"res","orgId":107,"installWay":null},"checked":false,"chkDisabled":false,"isHidden":false,"open":false,"relationName":null},{"id":"camera-42","label":"出入口","isParent":false,"cls":"ico m-gun","parentId":"107","children":null,"extra":{"channelNo":1,"indexCode":"001128","ezvizCameraCode":null,"fav":0,"realId":"42","type":"res","orgId":107,"installWay":null},"checked":false,"chkDisabled":false,"isHidden":false,"open":false,"relationName":null}];
        		if(OrgTreeResult){
        			realId = orgId;
               		var zTreeNodes=[];
                    if (OrgTreeResult.nodes && OrgTreeResult.nodes.children) {
                       pushAll(OrgTreeResult.nodes.children, zTreeNodes);
                    }
                    if (OrgTreeResult.children) {
                       pushAll(OrgTreeResult.children, zTreeNodes);
                     } 
                 	
                     if(!zTreeNodes.length){
                          zTreeNodes=[];
                  
                      }else{
                    	  if(globalResId && globalResId==orgId){  
                    		  if(typeof maxLevel != 'undefined'){
                    			  var orgArray=filterTree(zTreeNodes,curLevel,maxLevel);
                    			  pushAll(orgArray, orgArrayLevel);                               	
                    		  }
                    	  }
                      } 
                  //return zTreeNodes;
        		}
        		/*settingRes.ajax = {
                        url : 'getOrgTree.action',
                        type : 'POST',
                        data : {
                            id : orgId,
                            append : 1
                        },
                        dataType : "json",
                        handleData : function(result) {
                       		realId = orgId;
                       		var zTreeNodes=[];
                            if (result.nodes && result.nodes.children) {
                               pushAll(result.nodes.children, zTreeNodes);
                            }
                            if (result.children) {
                               pushAll(result.children, zTreeNodes);
                             } 
                         	
                             if(!zTreeNodes.length){
                                  zTreeNodes=[];
                          
                              }else{
                            	  if(globalResId && globalResId==orgId){  
                            		  if(typeof maxLevel != 'undefined'){
                            			  var orgArray=filterTree(zTreeNodes,curLevel,maxLevel);
                            			  pushAll(orgArray, orgArrayLevel);                               	
                            		  }
                            	  }
                              } 
                          return zTreeNodes; 
                        }
        		   };*/
                    settingRes.callback.beforeTreeLoad=function(zNodes){
            			if(globalResId&&globalResId==orgId){
            				return true;
            			}else{
            				return false;
            			}
            		} ;
                    $("#zTreea").tree(settingRes);
        	})(); 
        }       
    }
    
    /**
     * 获取在resourceGroup中所有子节点(为了更新在线状态数据)
     */
    function getUpdateInitNode(resourceGroup,updateNode){
    	var parentNode=resourceGroup;
    	if(parentNode){
    		updateNode[parentNode.id]=1;
    		if(parentNode.children && parentNode.children.length>0){
    			for(var i=0;i<parentNode.children.length;i++){
    				getUpdateInitNode(parentNode.children[i],updateNode);
    			}
    		}
    	}
    }
    
    /**
     * 当curLevel小于maxLevel时，返回nodes中的组织，已组织面包屑的形式显示
     */
    function filterTree(nodes,curLevel,maxLevel){
    	var orgNodes=[];
    	if(curLevel<maxLevel){
    		for(var i=0;i<nodes.length;i++){
                if(nodes[i].extra.type == 'org'){
                	orgNodes.push(nodes[i]);
                	nodes.splice(i,1);
                	i--;
        		}
    		}
    	}
    	return orgNodes;
    }

    /**
     * 异步加载之前触发的函数，返回false不进行异步加载
     */
    function beforeAsyncNode(treeId, treeNode) {
    	//console.log("beforeAsyncNode:"+new Date().getTime());
        if (!treeNode) {
            return false;
        }
        return true;
    }

    /**
     * 双击监控点或者组织节点触发的事件。
     * 若是监控点进行视频播放；
     * 若是组织在预览界面时将组织下的监控点(数量为窗口数量)播放
     */ 
    function dblClickCamera(event, treeId, treeNode) {
    	debugger;
    	if(!treeNode || !treeNode.extra){
    		return;
    	}
    	if (typeof(onlineInfo)!='undefined'&&treeNode.extra.type == 'org'){    //使用onlineInfo区分是预览还是回放，预览使用该功能
    		var id = treeNode.id;
    		var name = treeNode.label;
    		preview_obj.playOrgCamera(id,name);
    	}else if(typeof(onlineInfo)!='undefined' && treeNode.extra && treeNode.extra.type == 'device'  && treeNode.extra.deviceDetailType != 213 && treeNode.extra.deviceDetailType != 230){  //双击非监控大鹰眼设备,由于其下已经挂载了监控点，因此直接播放即可。
    		if(treeNode.children.length !=0 ){
    			var deviceCameras=[];
    			for(var i=0;i<treeNode.children.length;i++){
    				deviceCameras.push({id:treeNode.children[i].extra.realId,name:treeNode.children[i].label,intelCode:treeNode.children[i].extra.intelCode,intelChannelNo:treeNode.children[i].extra.intelChannelNo,indexCode:treeNode.children[i].extra.indexCode});
    			}
    			preview_obj.playDeviceOrgCameras(deviceCameras);
    		}
    	}else if (treeNode.extra.type == 'res' && treeNode.extra.realId) {
            var id = treeNode.extra.realId;
            var intelCode = "";
            var intelChannelNo = "";
            if(treeNode.extra.isIntel){
            	intelCode = treeNode.extra.intelCode;
            	intelChannelNo = treeNode.extra.intelChannelNo;
            }
            var cascadeCode="";
            if(treeNode.extra.cascadeCode){
            	cascadeCode=treeNode.extra.cascadeCode;
            }
            playCamera(id,treeNode.label,intelCode,intelChannelNo,treeNode.extra.indexCode,treeNode.extra.ezvizCameraCode,cascadeCode);
        }else if(typeof(onlineInfo)!='undefined' && treeNode.extra.type == 'device' && treeNode.extra && treeNode.extra.deviceDetailType == 213){   //进入大鹰眼播放模式
        	if(treeNode.children.length ==2 ||treeNode.children.length ==3){
        		var hawkeyeCameras=[];
        		for(var i=0;i<treeNode.children.length;i++){
        			hawkeyeCameras.push({id:treeNode.children[i].extra.realId,name:treeNode.children[i].label,intelCode:treeNode.children[i].extra.intelCode,intelChannelNo:treeNode.children[i].extra.intelChannelNo,indexCode:treeNode.children[i].extra.indexCode,channelNo:treeNode.children[i].extra.channelNo});
        		}
        		preview_obj.playHawkeyeDevice(hawkeyeCameras);
        	}else{
        		jSticky(language1['vms.preview.preview.js.noenterhaweyemodeplay'], {
					type : "attention"
				});
        	}
        }else if(typeof(onlineInfo)!='undefined' && treeNode.extra.type == 'device' && treeNode.extra && treeNode.extra.deviceDetailType == 230){   //红外热成像设备
        	if(treeNode.children.length == 2){
        		var infraredThermalImageryCameras=[];
        		for(var i=0;i<treeNode.children.length;i++){
        			infraredThermalImageryCameras.push({id:treeNode.children[i].extra.realId,name:treeNode.children[i].label,intelCode:treeNode.children[i].extra.intelCode,intelChannelNo:treeNode.children[i].extra.intelChannelNo,indexCode:treeNode.children[i].extra.indexCode,channelNo:treeNode.children[i].extra.channelNo});
        		}
        		preview_obj.playInfraredThermalImageryDevice(infraredThermalImageryCameras);
        	}else{
        		
        		jSticky(language['vms.preview.preview.js.infraredthermalimagingcameradoesnotsupport1x2'], {
					type : "attention"
				});
        	}
        }else if(treeNode.extra.type == 'capture' && treeNode.extra.realId){ //图片监控
        	
        	 var id = treeNode.extra.realId;
             var capturetime=0;
             if(treeNode.extra.capturetime){
            	 capturetime = treeNode.extra.capturetime;
             }
             playCamera(id, treeNode.label,treeNode.extra.indexCode,treeNode.extra.capturetype,treeNode.extra.capturetime,treeNode.extra.timeValue);
        }
    }
    
    /**
     * 单击监控点发生的事件
     */
    function onClickCamera(event, treeId, treeNode) {
    	if(treeNode && treeNode.extra && treeNode.extra.type == "org")return;
        if (treeNode && treeNode.extra && treeNode.extra.type == 'res' && treeNode.extra.realId) {
            var id = treeNode.extra.realId;
            try{
            	selectCamera(id, treeNode.label, treeNode.extra.indexCode,treeNode.extra.ezvizCameraCode,treeNode.extra.cascadeCode);
            }catch(e){
            }
        }
    }
    
    onClickSearch = function(id, name, indexCode, ezvizCameraCode,cascadeCode){
    	try{
    		selectCamera(id, name, indexCode, ezvizCameraCode,cascadeCode);
    	}catch(e){
        }
    };

    $("#topLevelResource").delegate("a", "click", function() {
        var auth = $(this).attr('data-auth');
        var id = $(this).attr('data-id');
        var l = $(this).attr('data-level');
        if(l==1&&level==0){
        	$('.tab-content .breadLine').css('display','none');        	
        }else{
        	getOrgPath(id);   //形成组织导航
        } 
         reLoadTree(id, l, level);   
         $('.breadLine').trigger('reLayout');  
        return false;
    });

    /***
     * 获取结点上要显示的标签.如：杭州区(30)/杭州区(1/30)/杭州区
     */
	function getNodeLabelWithOnlineInfo(node,label,id){
		if(typeof node != 'undefined' && node != null){
			var id = node.id;
			if(!onlineInfo || !onlineMap || !onlineMap[id]){
				return node.label;
			}
			var html = getNodeRealLabel(node.label);
			if(onlineInfo==0){
				return html + '(' +onlineMap[id].allCount + ")";
			}else if(onlineInfo==1){
				return html + '(<span style="color:black;">'+onlineMap[id].onlineCount+'</span>/<span  style="color:#888888;">' + onlineMap[id].allCount + '</span>)';
			}
			return node.label;
		}else{
			if(!onlineInfo || !onlineMap || !onlineMap[id]){
				return label;
			}
			var html = getNodeRealLabel(label);
			if(onlineInfo==0){
				return html + '(' +onlineMap[id].allCount + ")";
			}else if(onlineInfo==1){
				return html + '(<span style="color:black;">'+onlineMap[id].onlineCount+'</span>/<span  style="color:#888888;">' + onlineMap[id].allCount + '</span>)';
			}
		}
	}
	
	/***
	 * 获取树结点中真正的标签,如 杭州区(30)/杭州区(1/30)，只获得其中杭州区
	 * nodelabel：结点标签
	 */
	function getNodeRealLabel(nodelabel){
		if(nodelabel.indexOf("(<span style=\"color:")>=0&&nodelabel.lastIndexOf("(")!=-1&&nodelabel.lastIndexOf(")")==nodelabel.length-1){
			var index = nodelabel.lastIndexOf("(");
			var reallabel = nodelabel.substr(0, index);
			return reallabel;
		}
		return nodelabel;
	}

    var settingRes;

    /***
     * 当树展开的时候，去后台异步加载数据
     */
    function zTreeBeforeExpand(treeId, treeNode) {
        if (treeNode.extra && treeNode.extra.auth && !treeNode.extra.expend) {
            var treea = $("#zTreea").tree();
            treea.reAsyncChildNodes(treeNode, "!refresh");
            treeNode.extra.expend = 1;
        }
        return true;
    };

    /***
     *  异步加载以后，如果没有子节点，删除前面的“+”图标，节点自动变成叶子节点，更新展开之后子组织的在线统计数据
     */
    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        if (treeNode == null) {
            return;
        }
      //若有播放的监控点，则设置播放状态
        setNodeState(treeNode);
        //异步树在线统计
        online_pfc = 2;
        asyncTreeStatus(treeNode.children,treeNode.id);
    }   
    
    function viewtreeOnLoadSuccess(data) {
        var treea = $("#zTreea").tree();
        if (!treea) {
            return;
        }
        ztreeOnLoadSuccess(data);
    }

    /***
     * 树初始化加载成功回调的函数
     */
    function callOnLoadSuccessFunc(data) {
    	if(typeof(ztreeOnLoadSuccess)=='function'){
    		ztreeOnLoadSuccess(data);
    	}   
		var treea = $("#zTreea").tree();
		var nodes = null;
		if (treea){	
			nodes = treea.getNodes();
			setNodeState(nodes);
			 
		}
		
		//异步树在线统计，当有面包屑层级的时候需要用到，显示面包屑层级上的在线数
		online_pfc = 2;
		asyncTreeStatus(nodes,realId);
    }
	
	var openNodeOnlineMap = {};
	
	/**
	 * 组织展开时调用，根据该组织获得的监控点更新从该组织到根组织的在线数据
	 * nodes:组织下的所有孩子节点
	 * rId:组织ID
	 * breadOrgs:面包屑上的组织集合
	 */
	function updateOnlineStatusAfterTreeLoad(nodes,rId){
		var init = false;
		if(onlineReady){     //onlineReady=true:是否已经拿到全量同步的数据
			init = true;
		}
		var count = 0;
		var online= 0;
		var updateNode={};
		if (nodes && nodes.length > 0) {
			for(var i = 0; i < nodes.length; i++){
				var node = nodes[i];
				if(node.extra.expend && node.extra.type == 'device'){   //计算设备节点下的监控点数量
					var cameras = [];
					var camera_device_count=0;
					var camera_device_online=0;
					cameras = node.children;
					for(var j = 0; j < cameras.length; j++){
						var camera = cameras[j];
						if(camera.extra == undefined || camera.extra.type != 'res') continue;
						count++;						
						camera_device_count++;
						if(!camera.extra.disablecls) {
							online++;
							camera_device_online++;
						}
					}
					if(!onlineMap[node.id]){
						onlineMap[node.id]={};
					}
					onlineMap[node.id].id=node.id;
					onlineMap[node.id].allCount=camera_device_count;
					onlineMap[node.id].onlineCount=camera_device_online;
					updateNode[node.id]=1;
				}else {
				   if(node.extra == undefined) continue;
				   if(node.extra.type == 'org')  {
					   updateNode[node.id]=1;
					   continue;
				  }
				   count++;
				   if(!node.extra.disablecls) online++;
				}
			}
        }
		if(!init){
			openNodeOnlineMap[rId] = {};
			openNodeOnlineMap[rId].id = rId;
			openNodeOnlineMap[rId].allCount = count;
			openNodeOnlineMap[rId].onlineCount = online;
		}else{

			//获取组织面包屑上的内容
			var breadOrgs=$.map($('#topCategory a'),function(el){
				  return el.getAttribute('data-id');
			  });
			//获得rId节点下监控点的总数count和在线数online
			var updateNode = updateOnlineMap4OpenNode(count,online,rId,updateNode,breadOrgs);
			//更新页面上的数据
		    updateOnlineInfoLabel(onlineMap,updateNode);
			
		}
		
		
	}
	/**
	 * 返回从rId组织到根组织中需要更新的节点
	 * count:该组织下及其子组织监控点总数量
	 * online:该组织下及其子组织监控点在线数量
	 * rId:组织ID
	 * breadOrgs:组织面包屑上组织集合
	 */
	function updateOnlineMap4OpenNode(count,online,rId,updateNode,breadOrgs){
		var childCount = 0;
		var childOnline= 0;
		if(typeof updateNode == 'undefined'){
			updateNode={};
		}
		var treea=$('#zTreea').tree();
		var nodes=null;
		if(treea){
			var node=treea.getNodeById(rId);
			if(node == null){   //表示当前的rId是导航上的最后一个组织，需要将组织面包屑上的组织监控点统计信息也计算在内
				nodes=treea.getNodes();
			}else{
				nodes=node.children;
			}
			if(nodes && nodes.length > 0){
				var nId;
				for(var i=0;i<nodes.length;i++){
					if(nodes[i].extra && nodes[i].extra.type && nodes[i].extra.type == 'org'){
						nId=nodes[i].id;
						if(typeof onlineMap[nId] == 'undefined' ) continue;
						childCount+=onlineMap[nId].allCount;
						childOnline += onlineMap[nId].onlineCount;
					}
				}
			}
		}//当组织在面包屑层级上，且当前组织下无监控点，存在treea为null的情况，也要走以下的步骤进行判断是否有监控点增删的变化
		if(typeof breadOrgs != 'undefined' && breadOrgs.length>0){
			for(var i=0;i<breadOrgs.length;i++){
				nId=breadOrgs[i];
				if(typeof onlineMap[nId] != 'undefined'){
					childCount+=onlineMap[nId].allCount;
					childOnline += onlineMap[nId].onlineCount;
				}
			}
		}
		
		if(onlineMap[rId] == undefined){
			return updateNode;
		} 
		var oldAllCount = onlineMap[rId].allCount - childCount;
		var oldOnline = onlineMap[rId].onlineCount - childOnline;
				
		var changedAllCount = count - oldAllCount;
		var changedOnline =  online - oldOnline;
					
		var path = onlineMap[rId].path;
		var paths = path.split(',');
		for(var i = 0; i < paths.length; i++){
			var p = paths[i];
			if(p){
				if(onlineMap[p] == undefined){
					return updateNode;
				}
				onlineMap[p].allCount = onlineMap[p].allCount + changedAllCount;
				onlineMap[p].onlineCount = onlineMap[p].onlineCount + changedOnline;
				updateNode[p] = 1;
			}
		}
		return updateNode;
	}
	
	/**
	 * 在组织树中根据组织ID找到组织节点
	 * parent: 组织树
	 * id: 要找的组织节点ID
	 * 返回：id对应的在组织节点
	 */
	function findChildOrg(parent,id){
		if(parent.id == id){
			return parent;
		}
		var children = parent.children;
		if(children && children.length > 0){
			for(var i = 0; i < children.length; i++){
				var node = findChildOrg(children[i],id);
				if(node) return node;
			}
		}
		return null;
	}
	/**
	 * zTree的配置采用Json格式
	 * view(可视界面相关配置)
	 * data(数据相关配置)
	 * check(复选框相关配置)
	 * callback(各类事件的回调函数配置)
	 * async(zTree异步加载配置)
	 */
    function getSettingRes() {
        return {
        	initBigData: false,
            view : {
                removeHoverDom : removeHoverDom,
                nameIsHTML : true,
                showTitle : showTitleForTree,
                dblClickExpand: false
            },
           /* async : {
                enable : true,
                url : "getOrgTree.action",
                autoParam : ["id"],
                otherParam : {
                    append : 0
                }
            },*/
            data: {
        		key: {
        			title: "relationName"
        		}
        	},
            callback : {
                onDblClick : dblClickCamera,
                onClick : onClickCamera,
                beforeAsync : beforeAsyncNode,
                beforeExpand : zTreeBeforeExpand,
               	onAsyncSuccess : zTreeOnAsyncSuccess,
                initNode : callOnLoadSuccessFunc,
				dataEmpty:callOnLoadSuccessFunc
            }
        };
    }
    
    /**
     * 在节点关联球机时，将关联的球机的名称进行显示
     */
    function showTitleForTree(treeId, treeNode) {
    	if(treeNode && treeNode.extra && treeNode.relationName && treeNode.relationName != ''){
    		return true;
    	}else{
    		return false;
    	}
    };
    
    initMonResource();
	var onlineInterval = null;
    function initMonResource() {
        // 默认选中系统组织资源树
        if (0 == res_id) {    //表示无数据
            //$('#monResource').addClass("simple");
        } else if (level == 0) {           //不显示组织面包屑，显示完整资源树
        	init=true;
            $("#zTreea").hide();           
            settingRes = getSettingRes();
           var treea= $.fn.zTree.init($("#zTreea"), settingRes, resourceGroup);
            startExpandToUserOrg(treea,hasExpandToUserOrg,needExpandOrgIds,init);
            $("#loading").remove();
            $("#zTreea").show();
        } else if (resourceGroup && !resourceGroup.emtpy) {    //需要显示面包屑
        	if(hasExpandToUserOrg==0){         //不展开到用户所在组织，则组织导航显示一级，面包屑显示二级组织，资源树显示一级组织下的监控点
        		 getOrgPath(res_id);   //形成组织导航
                 settingRes = getSettingRes();
                 reLoadTree(res_id, res_level,level);
        	}else{
        	    init=true;
	            if(needExpandOrgIds.indexOf(res_id)>-1){   //将 needExpandOrgIds 中从根目录到res_id的 id全部删除，剩下的部分用于展开到组织用户使用
	                while(needExpandOrgIds.length != 0 && needExpandOrgIds[0] != res_id){
	                	needExpandOrgIds.shift();
	                }
	                if(needExpandOrgIds.length != 0){
	                	needExpandOrgIds.shift();
	                }
	            }
        	}
        }      
        online_pfc = 2;
    	asyncTreeStatus(null,0);
        //考虑
	    if (typeof(onlineInfo)!='undefined' && onlineInterval == null && window.onlineInfo==1) {
            onlineInterval = setInterval(asyncTreeStatus, checkPeriod * 60 * 1000);
        }
    }
    
    /**
     * 将资源树展开组织
     * tree: 树对象
     * needExpandOrgId:需要展开的组织ID   该参数主要用于在层级为0的情况下通过该值展开资源树到用户所属组织
     * end:表示是否继续展开
     */
    function expandToUserOrg (tree,needExpandOrgId,end){
    	if(init&&tree){
      	  node=tree.getNodeByTId("zTreea_id_"+needExpandOrgId);
    		if(node){    
    			tree.expandNode(node, true, false, false, true);
    			if(end){   
    				init=false;
    			}
    		}else{
    			init=false;
    		}
        }
    }
    
    /**
     * 展开到特定组织
     * hasExpandToUserOrg   是否展开到用户所在组织
     * needExpandOrgIds     需要展开的组织从根目录到用户所在组织的id集合，从头向尾展开，每展开一个，就将该变量从该字段中去掉
     */
    function startExpandToUserOrg(treea,hasExpandToUserOrg,needExpandOrgIds,init){
    	if(hasExpandToUserOrg==1 && init){
     	   while(needExpandOrgIds.length!=0){
     		   var needExpandOrgId=needExpandOrgIds.shift();
     		   if(needExpandOrgId!='' && Number(needExpandOrgId)){
     			   if(needExpandOrgIds.length == 0){
     				   expandToUserOrg(treea,needExpandOrgId,true);	
     			   }else{
     				   expandToUserOrg(treea,needExpandOrgId,false);	
     			   }
                  break;
     		   }
     	   }        	     
        }
    }
    
    /**
     * 异步树在线统计
     * nodes: 父节点下的节点数组
     * treeId: 父亲组织id
     * */
	function asyncTreeStatus(nodes,treeId){
		if (typeof(onlineInfo)!='undefined'){
	    	var option={
	        	url : 'getOnlineInfo.action',
	        	type : 'POST',
	        	data : {
	        		onlinePfc : online_pfc,
	        		id:treeId
	            },   		
	            dataType : "json",
	            success : function(result) {
	            	if(online_pfc == 2){
	            	if (result.success && result.onlineCountInfos&& result.onlineCountInfos.length) {
	            		
	                    for (var i = 0; i < result.onlineCountInfos.length; i++) {
	                        var onlineInfo = result.onlineCountInfos[i];
	        				var id = onlineInfo.id;
	        				onlineMap[id] = {};
	                        onlineMap[id].id = id;
	                        onlineMap[id].allCount = parseInt(onlineInfo.allCount);
	                        onlineMap[id].onlineCount = parseInt(onlineInfo.onlineCount);
	                        onlineMap[id].path = onlineInfo.path;   
	                    }
	                    
	                    if(treeId > 0) {
	                    	onlineReady = true;
	                    
		                    if(level > 0){//显示面包屑层级的在线数
			                    updateOnlineInfo(onlineMap, resourceGroup,onlineMap);
			                    updateOnlineInfoLabel(onlineMap,onlineMap);
			                }
		                    	
		                    if(init){//若需要展开组织，则展开。topNode节点在initMonResource已展开，所以只需判断treeId>0的情况
		                    	var treea = $("#zTreea").tree();
								startExpandToUserOrg(treea,hasExpandToUserOrg,needExpandOrgIds,init);
								openOrgArray.push(treeId);
				    		}
		                    updateOnlineStatusAfterTreeLoad(nodes,treeId);
	                    }else{
	                    	updateOnlineInfoLabel(onlineMap,onlineMap);
	                    }
	                } else {
	                	updateOnlineStatusAfterTreeLoad(nodes,treeId);
	                	updateOnlineInfoLabel(onlineMap,onlineMap);
	                }
	                online_pfc = 1;
	        	}else {
	        		processIncrementalOnlineInfo(result);
	        	}
	            }
	        };
	    	
	    	if(online_pfc==1){ 
	    		var treea = $("#zTreea").tree();
	    		if(treea){
	    			var resIndexCodes=[];
	    			var nodes = treea.transformToArray(treea.getNodes());
	    			for(var i=0;i<nodes.length;i++){
	    				if(nodes[i].isParent==false && nodes[i].extra && nodes[i].extra.type=='res'){
	    					resIndexCodes.push(nodes[i].extra.indexCode);
	    				}
	    			}
	    			if(resIndexCodes.length!=0){
	    				$.extend(option.data,{resIndexCodes:resIndexCodes});
	    				$.extend(option,{traditonal:true});
	    				$.ajax(option);
	    			}
	    		}
	    	}else
	          $.ajax(option);
		}
		if (typeof(onlineInfo)=='undefined' ){
			var treea = $("#zTreea").tree();
        	if(init && treeId > 0){     //若需要展开组织，则展开
				startExpandToUserOrg(treea,hasExpandToUserOrg,needExpandOrgIds,init);
				openOrgArray.push(treeId);
			}
        	if(nodes != null && nodes.length == 0){//若该组织下没有监控点，删除该组织的+/-标志
        		var node = treea.getNodeById(treeId);
        		treea.removeChildNodes(node);
        	}
		}
    }
	
	/***
     * 增量更新树结点上的监控点总数及在线总数,同时更新监控点在线状态
     * @param result     
     */
	function processIncrementalOnlineInfo(result){
		if (result.success && result.onlineInfos) {
			var isChange = 0;
			var updateNode  = {};
			var treea = $("#zTreea").tree();
			for (var i = 0; i < result.onlineInfos.length; i++) {
                var onlineInfo = result.onlineInfos[i];
                //如果树不为空，找到状态更新的节点
        		 if (treea) {
				 	 var node = treea.getNodeById("camera-" + onlineInfo.id);
					 if(!node) continue;
					 var orgId = node.extra.orgId;//得到他所在组织的id
					 updateNode[orgId] = 1;//要更新的组织
					 if (onlineInfo.online == 1) {//如果ajax返回的结果里的online状态为1.
						 if(node.extra.disablecls!='disabledNode'){ 
							 continue;
						 }
					 	onlineMap[orgId].onlineCount = onlineMap[orgId].onlineCount + 1;//onlineMap是一个存放所有组织的数组。onlineMap中某个组织的在线数+1，
						treea.setNodeDisabled("camera-" + onlineInfo.id,0);//设置某个camer的disable为false；
						//ie-8下disabled仍然是灰色的，所以这里去除他disabled属性
						$("#zTreea_id_camera-"+onlineInfo.id+"_a").removeAttr("disabled");
						node.extra.disablecls='';
						var parents = onlineMap[orgId].path.split(',');//找到该camera所有的父节点的id。
						for(var j = 0; j < parents.length; j++){
							var pId = parents[j];
							if(!pId || pId == orgId) continue;//如果节点为空，或者是当前camera所在的组织，则不进行onlineCount的更改。
							onlineMap[pId].onlineCount = onlineMap[pId].onlineCount + 1;
							updateNode[pId] = 1;//对改组织进行标记，需要更改。
						}
					 }else{
						 if(node.extra.disablecls=='disabledNode'){
							 continue;
						 }
					 	onlineMap[orgId].onlineCount = onlineMap[orgId].onlineCount - 1;
						treea.setNodeDisabled("camera-" + onlineInfo.id,1);
						$("#zTreea_id_camera-"+onlineInfo.id+"_a").attr("disabled","disabled");
						node.extra.disablecls='disabledNode';
						var parents = onlineMap[orgId].path.split(',');
						for(var j = 0; j < parents.length; j++){
							var pId = parents[j];
							//pid!=orgId
							if(!pId || pId == orgId) continue;
							onlineMap[pId].onlineCount = onlineMap[pId].onlineCount - 1;
							updateNode[pId] = 1;
						}
					 }
					 var parent=node.getParentNode();
					 if(parent && parent.extra.type == 'device'){
					     onlineMap[parent.id].onlineCount = onlineMap[parent.id].onlineCount + 1;
						 updateNode[parent.id] = 1;
					 }
					 isChange = 1;//标记isChange为1
				 }
            }
			if(isChange){
            	updateOnlineInfoLabel(onlineMap,updateNode);//更新结点的颜色  灰色?黑色
			}
		}
	}
	
	/***
	 * 更新结点上的数字
	 * onlineMap :存放所有组织的在线数据，其下在线监控点数量/监控点总数量
	 * updateNode：需要更新页面显示数据的组织结点
	 */
    function updateOnlineInfoLabel(onlineMap,updateNode) {
    	 // update topLevelResource
        $('#topLevelResource a').each(function() {
            var id = $(this).attr("data-id");
            if (updateNode[id]) {
				 var onlineInfo = onlineMap[id];
                var html = $(this).html().split('(');
                if(window.onlineInfo==1){
                	 $(this).html(html[0] + '(<span style="color:black;">'+onlineInfo.onlineCount + "</span>/"+'<span style="color:#888888;">'
                             + onlineInfo.allCount + '</span>)');
                }else if(window.onlineInfo==0){
                	$(this).html(html[0] + '(' + onlineInfo.allCount + ")");
                }
            }
        });

        $('#topLevelResource .end-li').each(function() {
            var id = $(this).attr("data-id");
            if (updateNode[id]) {
           	    var onlineInfo = onlineMap[id];
           	    var html = $(this).html().split('(<span style');
                if(window.onlineInfo==1){
               	   $(this).html(html[0]  + '(<span style="color:black;">'+onlineInfo.onlineCount +'</span>/<span style="color:#888888;">' + onlineInfo.allCount + '</span>)');
                }else if(window.onlineInfo==0){
                   $(this).html(html[0] + '(' + onlineInfo.allCount + ")");
                }               
            }
        });
        // 更新树节点状态
        var treea = $("#zTreea").tree();
        if (treea) {
            if (onlineMap) {
                for (var key in updateNode) {
                    var onlineInfo = onlineMap[key];//一个需要更新的组织节点
					if(!onlineInfo) continue;
                    var node = treea.getNodeById(onlineInfo.id);
                    if (node && node.extra && (node.extra.type == 'org' || node.extra.type == 'device')) {
                        var id = node.id;
                        var html = getNodeRealLabel(node.label);

                        if(html.indexOf('\(\d\/\d\)')>-1){
                        	var htm = html.split('\(\d\/\d\)');
                        	html = htm[0];
                        }
                          
                        if(window.onlineInfo==1){
                        	node.label = html + '(<span style="color:black;margin:0;">'+onlineInfo.onlineCount+'</span>/<span style="color:#888888;margin:0;">' + onlineInfo.allCount  + "</span>" + ")";
                        }else if(window.onlineInfo==0){
                        	node.label = html + '(' + onlineInfo.allCount + ")";
                        }
                        if (onlineInfo.allCount == 0) {// 当只有子组织没有子监控点的时候                        	
							var noChildren = true;
							if(node.isParent && node.children && node.children.length > 0){
								for(var kk = 0; kk < node.children.length;kk++){ 
									if(node.children[kk].extra.type == 'org' || node.children[kk].extra.type == 'device'){
									    noChildren = false;
										break;
									}
								}
							}
							if (noChildren) {  //如果其没有子组织将孩子移除
								treea.removeChildNodes(node);
							}
                        }
                        treea.updateNode(node);
                    }
                }
            }
        }
    }
    /*
     * 更新组织label信息及是否是父组织的信息
     * onlineMap：存放所有组织的在线数据，其下在线监控点数量/监控点总数量
     * parent:所有组织
     * updateNode：需要更新的结点。参数没有作用
     */
    function updateOnlineInfo(onlineMap, parent,updateNode) {
        if (!parent) {
            return;
        }
        for(var id in updateNode){
        	var onlineInfo = onlineMap[id];
            if (onlineInfo) {
            	var node=findChildOrg(parent,id);
            	if(null != node){
            		 var html = getNodeRealLabel(node.label);
                     if(window.onlineInfo==1){
                     	node.label =html + '(<span style="color:black;">'+onlineInfo.onlineCount+'</span>/<span style="color:#888888;">' + onlineInfo.allCount  + "</span>" + ")";//更新结点上在线结点数
                     }else if(window.onlineInfo==0){
                     	node.label = html + '(' + onlineInfo.allCount + ")";//更新结点上在线结点数
                     }           
                     if (onlineInfo.allCount == 0) {
         				if(node.isParent && node.children && node.children.length > 0){
         					node.isParent = false;
         					for(var kk = 0; kk < node.children.length;kk++){ 
         						if(node.children[kk].extra.type != 'res'){
         						    node.isParent = true;
         							break;
         						}
         					}
         				}
                     }
            	}           
            }
        }      
    }
    
    function removeHoverDom(treeId, treeNode) {
        if (treeNode.isParent == true)
            return;
        // 移除所有操作
        $("#diyBtnFav_" + treeNode.id).unbind().parent().remove();
        $(".tipsy").remove();
    }
});
/***
 * 将树中监控点设为播放状态
 * cameraId ：监控点ID
 */
function addPlayingStatus(cameraId){
	var treea = $("#zTreea").tree();
	if(!treea){
		return;
	}
	var node = treea.getNodeById("camera-" + cameraId);
	if(!node){
		return;
	}
	if(node.cls.indexOf("-playing") >= 0){
		
	}else{
		node.cls = node.cls + "-playing";
		treea.updateNode(node);
	}
}


/***
 * 清除树中对应监控点的播放状态
 * cameraId ：监控点ID
 */
function clearPlayStatus(cameraId){
	var treea = $("#zTreea").tree();
	if(treea){
		var node = treea.getNodeById("camera-" + cameraId);
		if(!node){
			return;
		}
		if(node.cls.indexOf("-playing") > 0){
			node.cls = node.cls.replace("-playing","");
			treea.updateNode(node);
		}
	}					
}

/***
 * 清除收藏夹树中对应监控点的播放状态
 * cameraId ：监控点ID
 */
function clearPlayStatusInFav(cameraId){
	var treeb = $("#zTreeb").tree();
	if(treeb){
		var node = treeb.getNodeById("camera-" + cameraId);
		if(!node){
			return;
		}
		if(node.cls.indexOf("-playing") > 0){
			node.cls = node.cls.replace("-playing","");
			treeb.updateNode(node);
		}
	}					
}

/**
 * 清除树中某个节点的选中状态
 * @param treeId
 * @param cameraId
 */
function clearSelectedStateInTree(treeId,cameraId){
	var tree=$("#"+treeId).tree();
	if(tree){
		if(typeof cameraId == 'undefined'){
			tree.cancelSelectedNode();
			return;
		}
		var node=tree.getNodeById("camera-"+cameraId);
		if(!node){
			return;
		}
		tree.cancelSelectedNode(node);
	}
}

/**
 * 取消某个节点在多个树中的选中状态
 * @param cameraId
 */
function clearSelectedState(cameraId){
	clearSelectedStateInTree("zTreeb",cameraId);
	clearSelectedStateInTree("zTreea",cameraId);
}

/**
 * 某个节点下正在播放的多个监控点设置状态（播放状态、选中状态）
 */
function setNodeState(treeNode){
	 if ((treeNode.children && treeNode.children.length > 0 && checkHasCamera(treeNode.children))||(treeNode.length && treeNode.length > 0)) {
	   try{
		   var _obj = null;
		   if(typeof preview_obj !='undefined' && typeof preview_obj.win_status !='undefined'){
			   _obj = preview_obj;
		   }
		   if(typeof playback_Obj !='undefined' && typeof playback_Obj.win_status !='undefined'){
			   _obj = playback_Obj;
		   }
			   
     	if(_obj != null){
     		for(var indexcode in _obj.win_status){     			
     			if(!isNaN(indexcode) && _obj.win_status[indexcode].count >0){ 
     				var cameraId=_obj.win_status[indexcode].cameraId;       				
     				if(!isNaN(cameraId)){
     					addPlayingStatus(cameraId);
     					addPlayingStatusInFav(cameraId);
     				}
     			}
     		}
     	}
	   }catch(e){}
     }
	 
	 setSelectedState($("#zTreea").tree(),$("#zTreeb").tree());
	 setSelectedState($("#zTreeb").tree(),$("#zTreea").tree());
}

/**
 * 检查nodes中是否含有监控点结点
 * @param nodes
 * @returns {Boolean}
 */
function checkHasCamera(nodes){
	for(var i=0;i<nodes.length;i++){
		if(nodes[i].extra && (nodes[i].extra.type == 'res'||nodes[i].extra.type == 'fav')){
			return true;
		}else if(nodes[i].children && checkHasCamera(nodes[i].children)){
			return true;
		}
	}
	return false;
}

/**
 * treea选中treeb中选中的监控点
 * 父节点选中展开
 * @param treea
 * @param treeb
 */
function setSelectedState(treea, treeb){
	if(treea && treeb){
		var selectedNodes=treeb.getSelectedNodes();
		var node=null;
		for(var i=0;i<selectedNodes.length;i++){
		  node=treea.getNodeById(selectedNodes[i].id);
		  if(node){
			  treea.selectNode(node,false);
		  }
		}
	}
}
